import { appTokenInstance } from "../utils/appToken";
import { appRequestUrl } from "../utils/config";
import { JudgmentExpiration } from "../utils/judgmentExpiration";
import { loginInstance } from "../utils/login";
import { resultProps } from "../utils/type";

interface requestParams {
  url: string
  method: string
  params?: object
  data?: object
  timeout?: number
}
enum METHOD_TYPE {
  'GET' = 'GET',
  "OPTIONS" = "OPTIONS",
  "HEAD" = "HEAD",
  "POST" = "POST",
  "PUT" = "PUT",
  "DELETE" = "DELETE",
  "TRACE" = "TRACE",
  "CONNECT" = "CONNECT"
}

//url
let baseUrl = appRequestUrl



//默认需要携带token访问的接口
const isToken: string[] = [
  '/api/user/portalUser/info',
  '/api/user/portalUser/update/info',
  '/api/mall/order/create/wx',
  '/api/mall/order/list',
  '/api/mall/order/cancel',
  '/api/mall/order/query/create',
  '/api/system/problem/add',
  '/api/mall/order/signUp/info'
]

interface headerProps {
  "content-type": string
  "cxl-token"?: string
  "cxl-client-type"?: string
  "app-token"?: string
}

export const http = async (params: requestParams) => {

  // set header options
  const headerOptions: headerProps = {
    "content-type": "application/json",
    "cxl-client-type": "APP"
  }

  //get 请求设置"content-type"请求头为"application/x-www-form-urlencoded;charset=utf-8"
  if (params.method === 'GET') {
    headerOptions["content-type"] = "application/x-www-form-urlencoded;charset=utf-8"
  }

  if (isToken.includes(params.url)) {
    //需要token
    let token = wx.getStorageSync('accessToken');
    if (token) {
      //存在token 判断当前token是否过期
      const expireTime = wx.getStorageSync('expire') || 0
      const loginTime = wx.getStorageSync('loginTime') || 0
      const isExpire = new JudgmentExpiration().expire(expireTime, loginTime, true)
      if (isExpire) {
        //等待重新获取token
        loginInstance.JudgmentExpirationInstance.clear()
        await loginInstance.getToken()
        token = wx.getStorageSync('accessToken');
        headerOptions["cxl-token"] = token
      } else {
        headerOptions["cxl-token"] = token
      }

    } else {
      //token 不存在进行拦截
      wx.showToast({
        title: '请重新登录！',
        icon: 'none'
      });

      toLogin()

      return new Promise<resultProps>(resolve => {
        resolve({
          code: '0',
          message: '',
          result: null,
          status: false
        })
      })
    }
  }

  if (params.url !== '/api/user/admin/app-token') {
    //add 'app-token' to interface
    let appToken = wx.getStorageSync('appToken')
    if (appToken) {
      //存在token 判断当前token是否过期
      const appExpire = wx.getStorageSync('appExpire') || 0
      const appTokenLoginTime = wx.getStorageSync('appTokenLoginTime') || 0
      const isExpire = new JudgmentExpiration().expire(appExpire, appTokenLoginTime, false)
      if (isExpire) {

        //等待重新获取token
        appTokenInstance.JudgmentExpirationInstance.clear()
        await appTokenInstance.getToken().then((res) => {
          appToken = res
        })
        appToken = wx.getStorageSync('appToken')
        headerOptions["app-token"] = appToken
      } else {
        headerOptions["app-token"] = appToken
      }


      return requestData(params, headerOptions)
    } else {
      //等待获取apptoken接口返回，设置app-token请求头
      await appTokenInstance.getToken().then((res) => {
        appToken = res
      })
      headerOptions["app-token"] = appToken
      return requestData(params, headerOptions)
    }
  } else {
    return requestData(params, headerOptions)
  }
}

//请求数据 返回 promise 结果数据
const requestData = (params: requestParams, headerOptions: headerProps) => {
  return new Promise<resultProps>((resolve, reject) => {
    wx.request({
      url: baseUrl + params.url,
      method: METHOD_TYPE[params.method as keyof typeof METHOD_TYPE] || 'GET',
      header: headerOptions,
      data: params.data || params.params,
      success: (res: any) => {
        console.log('%cresult:', 'color:#000;font-size:16px;background:#ebebeb;padding:0 4px', baseUrl, params, res.data)
        // console.log('结果：', baseUrl, params)
        if (Number(res.data.code) === 200) {
          resolve(res.data)
        } else if (Number(res.data.code) === -1 || Number(res.data.code) === 30006 || Number(res.data.code) === 30007) {
          //访问凭证为空 没有token                   
          //token 无效
          wx.showToast({
            title: res.data.message, icon: 'none'
          });

          toLogin()

          reject()
        } else {
          //其它
          wx.showToast({
            title: res.data.message, icon: 'none'
          });
          reject()
        }
      },
      fail: (res) => {
        reject()
        wx.showToast({
          title: res.errMsg, icon: 'none'
        });
      },
    });
  })
}

function toLogin() {
  loginInstance.removeStorage()
  loginInstance.JudgmentExpirationInstance.clear()
  appTokenInstance.removeStorage()
  appTokenInstance.JudgmentExpirationInstance.clear()


  //获取路由
  const routes = getCurrentPages()
  const isIndexPage = routes[routes.length - 1].route === "pages/index/index"
  console.log('routes', routes)

  const t = setTimeout(() => {
    clearTimeout(t)
    if (isIndexPage) {
      wx.navigateTo({ url: '/pages/login/login' })
    } else {
      wx.redirectTo({ url: '/pages/login/login' })
    }

  }, 1000)
}
